<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class RoleService
{
    // 列表
    public static function index($data)
    {
        try {

            $limit = isset($data['limit']) ? intval($data['limit']) : 10;
            $limit = max(1, min($limit, 100)); // 限制在1-100之间

            //分页查询
            $studio = \app\admin\model\UserGroup::field('id,name,status')->order('id', 'desc')
                ->paginate($limit);

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => 'Server Error', 'state' => 'ERROR'];
        }
    }


    // 添加
    public static function add($data)
    {
        // 验证规则
        $validate = new Validate([
            'role_name' => 'require|unique:user_group,name',
    //            'rules' => 'require',
        ], [
            'role_name.require' => 'Role name is not empty',
            'role_name.unique' => 'Role name is already exists',
    //            'rules.require' => 'Rules is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $data['name'] = $data['role_name'];
            $data['status'] = 'normal';
            unset($data['role_name']);
            $result = \app\admin\model\UserGroup::create($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 编辑
    public static function edit($data)
    {
        // 验证输入是否为数组
        if (!is_array($data)) {
            return ['code' => 400, 'msg' => 'Invalid input data', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        // 验证规则
        $validate = new Validate([
            'role_name' => 'require|unique:user_group,name',
            // 'rules' => 'require',
        ], [
            'role_name.require' => 'Role name is not empty',
            'role_name.unique' => 'Role name is already exists',
            // 'rules.require' => 'Rules is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code' => 400, 'msg' => $validate->getError(), 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $data['name'] = $data['role_name'];
            $data['status'] = 'normal';
            unset($data['role_name']);
            $result = \app\admin\model\UserGroup::update($data);

            if ($result) {
                Db::commit();
                return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $result];
            } else {
                Db::rollback();
                return ['code' => 400, 'msg' => 'Failed', 'state' => 'FAILED', 'data' => null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 删除
    public static function del($data)
    {

        // 验证$data['id']是否为空且为数字
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $id = (int)$data['id']; // 强制类型转换

        // 查询学习馆数据
        $role = \app\admin\model\UserGroup::find($id);
        if (!$role) {
            return ['code'=>400, 'msg'=>'Role does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }

        // 启用事务删除数据
        Db::startTrans();
        try {
            $result = \app\admin\model\UserGroup::destroy($id);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            // 记录日志
            \think\facade\Log::error('删除用户组失败: '.$e->getMessage());
            return ['code'=>400, 'msg'=>'Database error', 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
    }


    // 获取身份下员工
    public static function getStaff($data)
    {
        // 验证输入参数
        if (!is_array($data) || empty($data['role']) || !is_numeric($data['role'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        try {
            // 查询学习馆数据
            $list = \app\admin\model\User::where('group_id', $data['role'])->select();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$list];
        } catch (\Exception $e) {
            return ['code'=>500, 'msg'=>'Server error', 'state'=>'INTERNAL_ERROR', 'data'=>null];
        }
    }


    
}
